const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * url：接口地址
 * method：请求方式，默认GET
 * data：请求参数
 * hideTipe：是否显示加载效果(布尔值)
 * sendtype：数据传递方式，默认以流的形式
 */
const $http = (url, data, method, hideTip = false, sendtype, base64) => {
  let promise = new Promise((resolve, reject) => {
    let typeobj = {}
    let header = {
      'content-type': 'application/json',
      'appKey': 'ADS_WeChat',
      'appSecret': '9acb6e599b28962c3b6347db4c665dc2'
    }
    if (method === 'POST') {
      if (sendtype && sendtype === 'JSON') {
        header['content-type'] = 'application/json'
        typeobj.dataType = 'json'
      } else {
        header['content-type'] = 'application/x-www-form-urlencoded'
      }
    }
    if (hideTip) {
      globalShowTip(true)
    } else {
      globalShowTip(false)
    }
    let _httparam = {
      url: url,
      data: data || {},
      method: method || 'GET',
      header: header,
      responseType: base64 ? 'arraybuffer' :'',
      success(res) {
        wx.hideLoading()
        if (res && res.data) {
          let _data = res.data
          resolve(res.data)
        }
      },
      fail(error) {
        console.log(error)
        wx.hideLoading()
        wx.showModal({
          title: '温馨提示',
          content: '网络异常，请检查网络！',
          success: function (res) {
          },
          showCancel: false
        })
        reject(error)
      }
    }
    wx.request(Object.assign(typeobj, _httparam))
  })
  return promise
}
const globalShowTip = (tog, tit) => {
  if (tog) {
    wx.showLoading({
      title: tit || '加载中...',
      mask: true
    })
  } else {
    wx.hideLoading()
  }
}

const getFrameById = (id = '#navigation',callBack=()=>{}) =>{
  var query = wx.createSelectorQuery();
  query.select(id).boundingClientRect();
  query.exec(function (res) {
    callBack(res[0] || null)
  })
}
// 批量获取元素的位置等
const getRect = (selector, all) => {
  return new Promise(resolve => {
      wx.createSelectorQuery()
          [all ? 'selectAll' : 'select'](selector)
          .boundingClientRect(rect => {
          if (all && Array.isArray(rect) && rect.length) {
              resolve(rect);
          }
          if (!all && rect) {
              resolve(rect);
          }
      })
          .exec();
  });
}

// 把base64 的二进制数据 写到本地
const fsm = wx.getFileSystemManager();
const FILE_BASE_NAME = 'tmp_base64src'; //自定义文件名

const base64src = (base64data, cb) => {
  const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
  if (!format) {
    return (new Error('ERROR_BASE64SRC_PARSE'));
  }
  const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
  const buffer = wx.base64ToArrayBuffer(bodyData);
  fsm.writeFile({
    filePath,
    data: buffer,
    encoding: 'binary',
    success() {
      cb(filePath);
    },
    fail() {
      return (new Error('ERROR_BASE64SRC_WRITE'));
    }
 })
}

function filterURL(url, type='ads') {
  // url 为固定的参数 如果url为相对地址,则返回绝对地址
  if (url) {
    var isHttps = url.indexOf('https://')
    var isHttp = url.indexOf('http://')

    if (isHttps > -1 || isHttp > -1) {
      return url
    } else {
      if(type == 'ads') {
        // return 'https://filedev.quanyou.com.cn/'+ url   // 测试环境
        return 'https://file200.quanyou.com.cn/'+ url // 正式环境
        } else {
          // return 'https://testimg.quanyou.com.cn/'+ url // 用于商城图片展示 装修攻略
          return 'https://gcenterimg.quanyou.com.cn/'+ url // 正式
        }
    }
  }
}

module.exports = {
  formatTime: formatTime,
  $http: $http,
  globalShowTip: globalShowTip,
  getFrameById,
  getRect,
  base64src,
  filterURL
}
